<template>
  <div class="app-container">
    <el-card shadow="never">
      <div slot="header" class="card-header">
        <span>房源租赁绑定</span>
        <el-button type="primary" size="mini" icon="el-icon-plus" @click="openCreate">
          新增绑定
        </el-button>
      </div>

      <el-form :inline="true" :model="queryParams" class="filter-form" label-width="80px">
        <el-form-item label="房源ID">
          <el-input v-model.trim="queryParams.houseId" placeholder="请输入房源ID" size="mini" />
        </el-form-item>
        <el-form-item label="租客ID">
          <el-input v-model.trim="queryParams.tenantUserId" placeholder="请输入租客ID" size="mini" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="mini">
            <el-option
              v-for="item in statusOptions"
              :key="item.code"
              :label="item.label"
              :value="item.code"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="mini" icon="el-icon-search" @click="handleQuery">搜索</el-button>
          <el-button size="mini" icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table :data="list" v-loading="loading" border>
        <el-table-column prop="leaseId" label="编号" width="90" align="center" />
        <el-table-column prop="houseId" label="房源ID" width="100" align="center" />
        <el-table-column prop="tenantUserId" label="租客ID" width="100" align="center" />
        <el-table-column prop="rentAmount" label="租金" width="120" />
        <el-table-column prop="depositAmount" label="押金" width="120" />
        <el-table-column prop="status" label="状态" width="140">
          <template slot-scope="scope">
            {{ translateStatus(scope.row.status) }}
          </template>
        </el-table-column>
        <el-table-column prop="startDate" label="起租日期" width="120" />
        <el-table-column prop="endDate" label="到期日期" width="120" />
        <el-table-column prop="remindDays" label="提醒天数" width="100" align="center" />
        <el-table-column label="操作" width="260" align="center">
          <template slot-scope="scope">
            <el-button type="text" size="mini" icon="el-icon-edit" @click="openEdit(scope.row)">编辑</el-button>
            <el-button type="text" size="mini" icon="el-icon-message" @click="openNotificationDrawer(scope.row)">通知</el-button>
            <el-button type="text" size="mini" icon="el-icon-document" @click="openBillDrawer(scope.row)">账单</el-button>
            <el-button type="text" size="mini" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="520px" destroy-on-close>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="110px">
        <el-form-item label="房源ID" prop="houseId">
          <el-input v-model.number="form.houseId" placeholder="请输入房源ID" />
        </el-form-item>
        <el-form-item label="租客ID" prop="tenantUserId">
          <el-input v-model.number="form.tenantUserId" placeholder="请输入租客ID" />
        </el-form-item>
        <el-form-item label="房东ID">
          <el-input v-model.number="form.landlordUserId" placeholder="可选，默认房源发布人" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option
              v-for="item in statusOptions"
              :key="item.code"
              :label="item.label"
              :value="item.code"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="起租日期">
          <el-date-picker v-model="form.startDate" type="date" placeholder="选择日期" value-format="yyyy-MM-dd" />
        </el-form-item>
        <el-form-item label="到期日期">
          <el-date-picker v-model="form.endDate" type="date" placeholder="选择日期" value-format="yyyy-MM-dd" />
        </el-form-item>
        <el-form-item label="租金">
          <el-input v-model.number="form.rentAmount" placeholder="月租金" />
        </el-form-item>
        <el-form-item label="押金">
          <el-input v-model.number="form.depositAmount" placeholder="押金" />
        </el-form-item>
        <el-form-item label="提醒天数">
          <el-input-number v-model="form.remindDays" :min="1" :max="180" />
        </el-form-item>
        <el-form-item label="合同链接">
          <el-input v-model.trim="form.contractUrl" placeholder="可填写合同文件链接" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model.trim="form.remark" type="textarea" :rows="2" />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="submitForm">保 存</el-button>
      </div>
    </el-dialog>

    <el-drawer
      title="通知管理"
      :visible.sync="notificationDrawer.visible"
      size="50%"
      destroy-on-close
    >
      <div class="drawer-toolbar">
        <div class="drawer-meta" v-if="notificationDrawer.lease">
          <span>租赁ID：{{ notificationDrawer.lease.leaseId }}</span>
          <span>房源ID：{{ notificationDrawer.lease.houseId }}</span>
          <span>租客ID：{{ notificationDrawer.lease.tenantUserId }}</span>
        </div>
        <el-button type="primary" size="mini" icon="el-icon-plus" @click="openNotificationDialog">
          新建通知
        </el-button>
      </div>
      <el-table
        :data="notificationDrawer.list"
        v-loading="notificationDrawer.loading"
        size="small"
        border
      >
        <el-table-column prop="title" label="标题" min-width="200" show-overflow-tooltip />
        <el-table-column prop="targetRole" label="对象" width="100">
          <template slot-scope="scope">{{ scope.row.targetRole === 'LANDLORD' ? '房东' : '租客' }}</template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="120">
          <template slot-scope="scope">
            <el-tag :type="translateNotificationStatus(scope.row.status).type">{{ translateNotificationStatus(scope.row.status).label }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="sendTime" label="发送时间" width="180" />
        <el-table-column label="操作" width="180" align="center">
          <template slot-scope="scope">
            <el-button type="text" size="mini" icon="el-icon-view" @click="openNotificationDetail(scope.row)">查看</el-button>
            <el-button type="text" size="mini" icon="el-icon-delete" @click="removeNotification(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-drawer>

    <el-dialog
      :title="notificationDialog.editing ? '编辑通知' : '新建通知'"
      :visible.sync="notificationDialog.visible"
      width="520px"
      destroy-on-close
    >
      <el-form ref="notificationForm" :model="notificationDialog.form" :rules="notificationDialog.rules" label-width="110px">
        <el-form-item label="发送对象" prop="targetRole">
          <el-select v-model="notificationDialog.form.targetRole" placeholder="请选择">
            <el-option label="租客" value="TENANT" />
            <el-option label="房东" value="LANDLORD" />
          </el-select>
        </el-form-item>
        <el-form-item label="标题" prop="title">
          <el-input v-model.trim="notificationDialog.form.title" maxlength="80" />
        </el-form-item>
        <el-form-item label="正文" prop="content">
          <el-input v-model.trim="notificationDialog.form.content" type="textarea" :rows="4" />
        </el-form-item>
        <el-form-item label="需要资料">
          <el-switch v-model="notificationDialog.form.requireSubmission" />
        </el-form-item>
        <el-form-item v-if="notificationDialog.form.requireSubmission" label="资料类型">
          <el-select
            v-model="notificationDialog.form.requiredTypes"
            multiple
            filterable
            allow-create
            default-first-option
            placeholder="选择或输入资料类型"
          >
            <el-option
              v-for="item in notificationDialog.materialOptions"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="notificationDialog.visible = false">取 消</el-button>
        <el-button type="primary" :loading="notificationDialog.loading" @click="submitNotification">提 交</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="通知详情"
      :visible.sync="notificationDetail.visible"
      width="700px"
      destroy-on-close
    >
      <el-descriptions v-if="notificationDetail.data" :column="2" border size="small">
        <el-descriptions-item label="标题">{{ notificationDetail.data.title }}</el-descriptions-item>
        <el-descriptions-item label="对象">{{ notificationDetail.data.targetRole === 'LANDLORD' ? '房东' : '租客' }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="translateNotificationStatus(notificationDetail.data.status).type">
            {{ translateNotificationStatus(notificationDetail.data.status).label }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="发送时间">{{ notificationDetail.data.sendTime || '-' }}</el-descriptions-item>
        <el-descriptions-item label="内容" :span="2">{{ notificationDetail.data.content || '-' }}</el-descriptions-item>
      </el-descriptions>

      <el-divider content-position="left">上传资料</el-divider>
      <el-table v-loading="notificationDetail.loading" :data="notificationDetail.materials" size="small" border>
        <el-table-column prop="fileName" label="文件名" min-width="220" show-overflow-tooltip />
        <el-table-column prop="contentType" label="类型" width="120" />
        <el-table-column prop="createTime" label="上传时间" width="180" />
        <el-table-column prop="status" label="状态" width="120">
          <template slot-scope="scope">
            <el-tag :type="translateMaterialStatus(scope.row.status).type">{{ translateMaterialStatus(scope.row.status).label }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center">
          <template slot-scope="scope">
            <el-button type="text" size="mini" :href="scope.row.fileUrl" target="_blank">预览</el-button>
            <el-button type="text" size="mini" @click="reviewMaterial(scope.row, 'APPROVED')">通过</el-button>
            <el-button type="text" size="mini" @click="reviewMaterial(scope.row, 'REJECTED')">驳回</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <el-drawer
      title="账单管理"
      :visible.sync="billDrawer.visible"
      size="50%"
      destroy-on-close
    >
      <div class="drawer-toolbar">
        <div class="drawer-meta" v-if="billDrawer.lease">
          <span>租赁ID：{{ billDrawer.lease.leaseId }}</span>
          <span>房源ID：{{ billDrawer.lease.houseId }}</span>
          <span>租客ID：{{ billDrawer.lease.tenantUserId }}</span>
        </div>
        <el-button type="primary" size="mini" icon="el-icon-plus" @click="openBillDialog()">
          新建账单
        </el-button>
      </div>
      <el-table :data="billDrawer.list" v-loading="billDrawer.loading" size="small" border>
        <el-table-column prop="title" label="标题" min-width="180" show-overflow-tooltip />
        <el-table-column prop="billType" label="类型" width="100" />
        <el-table-column prop="amount" label="金额" width="100" />
        <el-table-column prop="status" label="状态" width="120">
          <template slot-scope="scope">
            <el-tag :type="translateBillStatus(scope.row.status).type">{{ translateBillStatus(scope.row.status).label }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="dueDate" label="到期日" width="120" />
        <el-table-column label="操作" width="220" align="center">
          <template slot-scope="scope">
            <el-button type="text" size="mini" icon="el-icon-document" @click="viewBill(scope.row)">详情</el-button>
            <el-button type="text" size="mini" icon="el-icon-tickets" @click="openReceiptDialog(scope.row)">凭证</el-button>
            <el-button type="text" size="mini" icon="el-icon-delete" @click="removeBill(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-drawer>

    <el-dialog :title="billDialog.editing ? '编辑账单' : '新建账单'" :visible.sync="billDialog.visible" width="560px" destroy-on-close>
      <el-form ref="billForm" :model="billDialog.form" :rules="billDialog.rules" label-width="110px">
        <el-form-item label="账单类型" prop="billType">
          <el-select v-model="billDialog.form.billType" placeholder="请选择">
            <el-option label="租金" value="RENT" />
            <el-option label="水费" value="WATER" />
            <el-option label="电费" value="ELECTRIC" />
            <el-option label="网费" value="INTERNET" />
            <el-option label="其他" value="OTHER" />
          </el-select>
        </el-form-item>
        <el-form-item label="发送对象" prop="targetRole">
          <el-select v-model="billDialog.form.targetRole" placeholder="请选择">
            <el-option label="租客" value="TENANT" />
            <el-option label="房东" value="LANDLORD" />
          </el-select>
        </el-form-item>
        <el-form-item label="标题" prop="title">
          <el-input v-model.trim="billDialog.form.title" maxlength="80" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model.trim="billDialog.form.description" type="textarea" :rows="3" />
        </el-form-item>
        <el-form-item label="金额" prop="amount">
          <el-input-number v-model="billDialog.form.amount" :min="0" :precision="2" :step="1" />
        </el-form-item>
        <el-form-item label="币种">
          <el-input v-model.trim="billDialog.form.currency" placeholder="例如 CNY" />
        </el-form-item>
        <el-form-item label="账期开始">
          <el-date-picker v-model="billDialog.form.billingStart" type="date" value-format="yyyy-MM-dd" placeholder="选择日期" />
        </el-form-item>
        <el-form-item label="账期结束">
          <el-date-picker v-model="billDialog.form.billingEnd" type="date" value-format="yyyy-MM-dd" placeholder="选择日期" />
        </el-form-item>
        <el-form-item label="到期日">
          <el-date-picker v-model="billDialog.form.dueDate" type="date" value-format="yyyy-MM-dd" placeholder="选择日期" />
        </el-form-item>
        <el-form-item label="账单文件">
          <el-upload
            :action="billDialog.uploadUrl"
            :headers="billDialog.uploadHeaders"
            :on-success="handleBillUploadSuccess"
            :show-file-list="false"
            accept=".pdf,.jpg,.jpeg,.png"
          >
            <el-button type="primary" size="mini">上传文件</el-button>
            <span class="upload-tip" v-if="billDialog.form.billFileName">{{ billDialog.form.billFileName }}</span>
          </el-upload>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model.trim="billDialog.form.remark" type="textarea" :rows="2" />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="billDialog.visible = false">取 消</el-button>
        <el-button type="primary" :loading="billDialog.loading" @click="submitBill">提 交</el-button>
      </div>
    </el-dialog>

    <el-dialog title="账单详情" :visible.sync="billDetail.visible" width="680px" destroy-on-close>
      <el-descriptions v-if="billDetail.data" :column="2" border size="small">
        <el-descriptions-item label="标题">{{ billDetail.data.title }}</el-descriptions-item>
        <el-descriptions-item label="类型">{{ billDetail.data.billType }}</el-descriptions-item>
        <el-descriptions-item label="金额">{{ billDetail.data.amount }} {{ billDetail.data.currency }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="translateBillStatus(billDetail.data.status).type">{{ translateBillStatus(billDetail.data.status).label }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="账期">{{ billDetail.data.billingStart || '-' }} ~ {{ billDetail.data.billingEnd || '-' }}</el-descriptions-item>
        <el-descriptions-item label="到期日">{{ billDetail.data.dueDate || '-' }}</el-descriptions-item>
        <el-descriptions-item label="账单文件" :span="2">
          <el-link v-if="billDetail.data.billFileUrl" :href="billDetail.data.billFileUrl" type="primary" target="_blank">查看账单</el-link>
          <span v-else>-</span>
        </el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ billDetail.data.remark || '-' }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <el-dialog title="支付凭证" :visible.sync="receiptDialog.visible" width="680px" destroy-on-close>
      <el-table :data="receiptDialog.list" v-loading="receiptDialog.loading" size="small" border>
        <el-table-column prop="fileName" label="文件名" min-width="200" show-overflow-tooltip />
        <el-table-column prop="createTime" label="上传时间" width="180" />
        <el-table-column prop="status" label="状态" width="120">
          <template slot-scope="scope">
            <el-tag :type="translateReceiptStatus(scope.row.status).type">{{ translateReceiptStatus(scope.row.status).label }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center">
          <template slot-scope="scope">
            <el-button type="text" size="mini" :href="scope.row.fileUrl" target="_blank">预览</el-button>
            <el-button type="text" size="mini" @click="reviewReceipt(scope.row, 'APPROVED')">通过</el-button>
            <el-button type="text" size="mini" @click="reviewReceipt(scope.row, 'REJECTED')">驳回</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import { listHouseLease, addHouseLease, updateHouseLease, delHouseLease, fetchLeaseStatusOptions } from '@/api/house/lease'
import { listLeaseNotifications, createLeaseNotification, deleteLeaseNotifications, getLeaseNotification } from '@/api/house/notification'
import { reviewLeaseMaterial } from '@/api/house/material'
import { listLeaseBills, createLeaseBill, updateLeaseBill, deleteLeaseBills, getLeaseBill } from '@/api/house/bill'
import { reviewBillReceipt } from '@/api/house/billReceipt'
import { getToken } from '@/utils/auth'

export default {
  name: 'HouseLease',
  data() {
    return {
      loading: false,
      list: [],
      total: 0,
      statusOptions: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        houseId: undefined,
        tenantUserId: undefined,
        status: undefined
      },
      dialogVisible: false,
      dialogTitle: '新增绑定',
      submitLoading: false,
      form: {
        leaseId: undefined,
        houseId: undefined,
        tenantUserId: undefined,
        landlordUserId: undefined,
        status: 'PENDING_SIGN',
        startDate: undefined,
        endDate: undefined,
        rentAmount: undefined,
        depositAmount: undefined,
        remindDays: 30,
        contractUrl: '',
        remark: ''
      },
      rules: {
        houseId: [{ required: true, message: '请输入房源ID', trigger: 'blur' }],
        tenantUserId: [{ required: true, message: '请输入租客ID', trigger: 'blur' }],
        status: [{ required: true, message: '请选择状态', trigger: 'change' }]
      },
      notificationDrawer: {
        visible: false,
        loading: false,
        lease: null,
        list: []
      },
      notificationDialog: {
        visible: false,
        editing: false,
        loading: false,
        form: {
          leaseId: null,
          targetRole: 'TENANT',
          title: '',
          content: '',
          requireSubmission: false,
          requiredTypes: []
        },
        rules: {
          title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
          content: [{ required: true, message: '请输入内容', trigger: 'blur' }]
        },
        materialOptions: ['PASSPORT', 'VISA', 'PAYMENT_PROOF', 'IDCARD']
      },
      notificationDetail: {
        visible: false,
        data: null,
        materials: [],
        loading: false
      },
      billDrawer: {
        visible: false,
        loading: false,
        lease: null,
        list: []
      },
      billDialog: {
        visible: false,
        editing: false,
        loading: false,
        form: {
          leaseId: null,
          targetRole: 'TENANT',
          billType: 'RENT',
          title: '',
          description: '',
          amount: 0,
          currency: 'CNY',
          billingStart: '',
          billingEnd: '',
          dueDate: '',
          billFileKey: '',
          billFileUrl: '',
          billFileName: '',
          billFileContentType: '',
          billFileSize: null,
          remark: ''
        },
        rules: {
          billType: [{ required: true, message: '请选择账单类型', trigger: 'change' }],
          title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
          amount: [{ required: true, message: '请输入金额', trigger: 'change' }]
        },
        uploadUrl: process.env.VUE_APP_BASE_API + '/common/upload',
        uploadHeaders: {
          Authorization: 'Bearer ' + getToken()
        }
      },
      billDetail: {
        visible: false,
        data: null
      },
      receiptDialog: {
        visible: false,
        loading: false,
        list: [],
        billId: null
      }
    }
  },
  created() {
    this.loadStatusOptions()
    this.getList()
  },
  methods: {
    async loadStatusOptions() {
      try {
        const res = await fetchLeaseStatusOptions()
        this.statusOptions = (res.data && res.data.items) || []
      } catch (e) {
        this.statusOptions = []
      }
    },
    async getList() {
      this.loading = true
      try {
        const res = await listHouseLease(this.queryParams)
        this.list = res.rows || []
        this.total = res.total || 0
      } finally {
        this.loading = false
      }
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        houseId: undefined,
        tenantUserId: undefined,
        status: undefined
      }
      this.getList()
    },
    openCreate() {
      this.dialogTitle = '新增绑定'
      this.dialogVisible = true
      this.submitLoading = false
      this.form = {
        leaseId: undefined,
        houseId: undefined,
        tenantUserId: undefined,
        landlordUserId: undefined,
        status: (this.statusOptions[0] && this.statusOptions[0].code) || 'PENDING_SIGN',
        startDate: undefined,
        endDate: undefined,
        rentAmount: undefined,
        depositAmount: undefined,
        remindDays: 30,
        contractUrl: '',
        remark: ''
      }
    },
    openEdit(row) {
      this.dialogTitle = '编辑绑定'
      this.dialogVisible = true
      this.submitLoading = false
      this.form = Object.assign({}, row)
    },
    submitForm() {
      this.$refs.formRef.validate(async valid => {
        if (!valid) return
        this.submitLoading = true
        try {
          if (this.form.leaseId) {
            await updateHouseLease(this.form)
            this.$message.success('更新成功')
          } else {
            await addHouseLease(this.form)
            this.$message.success('创建成功')
          }
          this.dialogVisible = false
          this.getList()
        } finally {
          this.submitLoading = false
        }
      })
    },
    handleDelete(row) {
      this.$confirm('确定要删除该租赁记录吗？', '提示', {
        type: 'warning'
      }).then(async () => {
        await delHouseLease(row.leaseId)
        this.$message.success('删除成功')
        this.getList()
      }).catch(() => {})
    },
    translateStatus(code) {
      const target = this.statusOptions.find(item => item.code === code)
      return target ? target.label : code
    },
    openNotificationDrawer(row) {
      this.notificationDrawer.lease = row
      this.notificationDrawer.visible = true
      this.fetchNotifications()
    },
    async fetchNotifications() {
      if (!this.notificationDrawer.lease) return
      this.notificationDrawer.loading = true
      try {
        const res = await listLeaseNotifications({ leaseId: this.notificationDrawer.lease.leaseId, pageNum: 1, pageSize: 100 })
        this.notificationDrawer.list = res.rows || []
      } finally {
        this.notificationDrawer.loading = false
      }
    },
    openNotificationDialog() {
      const lease = this.notificationDrawer.lease
      if (!lease) return
      this.notificationDialog.visible = true
      this.notificationDialog.editing = false
      this.notificationDialog.loading = false
      this.notificationDialog.form = {
        leaseId: lease.leaseId,
        targetRole: 'TENANT',
        title: '',
        content: '',
        requireSubmission: false,
        requiredTypes: []
      }
    },
    submitNotification() {
      this.$refs.notificationForm.validate(async valid => {
        if (!valid) return
        this.notificationDialog.loading = true
        try {
          await createLeaseNotification(this.notificationDialog.form)
          this.$message.success('发送成功')
          this.notificationDialog.visible = false
          this.fetchNotifications()
        } finally {
          this.notificationDialog.loading = false
        }
      })
    },
    async openNotificationDetail(row) {
      this.notificationDetail.visible = true
      this.notificationDetail.loading = true
      try {
        const res = await getLeaseNotification(row.notificationId)
        const data = res.data || {}
        this.notificationDetail.data = data.notification || row
        this.notificationDetail.materials = data.materials || []
      } finally {
        this.notificationDetail.loading = false
      }
    },
    removeNotification(row) {
      this.$confirm('确定删除该通知吗？', '提示', {
        type: 'warning'
      }).then(async () => {
        await deleteLeaseNotifications(row.notificationId)
        this.$message.success('已删除')
        this.fetchNotifications()
      }).catch(() => {})
    },
    async reviewMaterial(material, status) {
      try {
        await reviewLeaseMaterial(material.materialId, { status, remark: '' })
        this.$message.success(status === 'APPROVED' ? '已通过' : '已驳回')
        if (this.notificationDetail.visible && this.notificationDetail.data) {
          await this.openNotificationDetail(this.notificationDetail.data)
        }
      } catch (e) {}
    },
    translateNotificationStatus(status) {
      const map = {
        ACKED: { label: '已确认', type: 'success' },
        COMPLETED: { label: '已完成', type: 'success' },
        SENT: { label: '已发送', type: 'info' }
      }
      return map[status] || { label: status || '-', type: 'info' }
    },
    translateMaterialStatus(status) {
      const map = {
        SUBMITTED: { label: '已提交', type: 'info' },
        APPROVED: { label: '已通过', type: 'success' },
        REJECTED: { label: '已驳回', type: 'danger' }
      }
      return map[status] || { label: status || '-', type: 'info' }
    },
    openBillDrawer(row) {
      this.billDrawer.lease = row
      this.billDrawer.visible = true
      this.loadBills()
    },
    async loadBills() {
      if (!this.billDrawer.lease) return
      this.billDrawer.loading = true
      try {
        const res = await listLeaseBills({ leaseId: this.billDrawer.lease.leaseId, targetUserId: this.billDrawer.lease.tenantUserId, pageNum: 1, pageSize: 100 })
        this.billDrawer.list = res.rows || []
      } finally {
        this.billDrawer.loading = false
      }
    },
    openBillDialog(bill) {
      const lease = this.billDrawer.lease
      if (!lease) return
      this.billDialog.visible = true
      this.billDialog.editing = !!bill
      this.billDialog.loading = false
      if (bill) {
        this.billDialog.form = Object.assign({}, bill)
      } else {
        this.billDialog.form = {
          leaseId: lease.leaseId,
          targetRole: 'TENANT',
          billType: 'RENT',
          title: '',
          description: '',
          amount: 0,
          currency: 'CNY',
          billingStart: '',
          billingEnd: '',
          dueDate: '',
          billFileKey: '',
          billFileUrl: '',
          billFileName: '',
          billFileContentType: '',
          billFileSize: null,
          remark: ''
        }
      }
    },
    handleBillUploadSuccess(response) {
      if (!response) return
      this.billDialog.form.billFileKey = response.fileName || ''
      this.billDialog.form.billFileUrl = response.url || ''
      this.billDialog.form.billFileName = response.realName || response.fileName || ''
      this.billDialog.form.billFileContentType = response.contentType || ''
    },
    submitBill() {
      this.$refs.billForm.validate(async valid => {
        if (!valid) return
        this.billDialog.loading = true
        try {
          const payload = Object.assign({}, this.billDialog.form)
          if (this.billDialog.editing) {
            await updateLeaseBill(payload.billId, payload)
          } else {
            await createLeaseBill(payload)
          }
          this.$message.success('保存成功')
          this.billDialog.visible = false
          this.loadBills()
        } finally {
          this.billDialog.loading = false
        }
      })
    },
    async viewBill(row) {
      const res = await getLeaseBill(row.billId)
      const data = res.data || {}
      this.billDetail.data = data.bill || row
      this.billDetail.visible = true
    },
    removeBill(row) {
      this.$confirm('确定删除该账单吗？', '提示', {
        type: 'warning'
      }).then(async () => {
        await deleteLeaseBills(row.billId)
        this.$message.success('已删除')
        this.loadBills()
      }).catch(() => {})
    },
    async openReceiptDialog(row) {
      this.receiptDialog.visible = true
      this.receiptDialog.billId = row.billId
      this.receiptDialog.loading = true
      try {
        const res = await getLeaseBill(row.billId)
        const data = res.data || {}
        this.receiptDialog.list = (data.receipts || []).map(item => Object.assign({ billId: row.billId }, item))
      } finally {
        this.receiptDialog.loading = false
      }
    },
    async reviewReceipt(receipt, status) {
      await reviewBillReceipt(receipt.receiptId, { status })
      this.$message.success(status === 'APPROVED' ? '已通过' : '已驳回')
      this.openReceiptDialog({ billId: this.receiptDialog.billId })
      this.loadBills()
    },
    translateBillStatus(status) {
      const map = {
        PENDING: { label: '待支付', type: 'warning' },
        PAID: { label: '已支付', type: 'success' },
        OVERDUE: { label: '已逾期', type: 'danger' }
      }
      return map[status] || { label: status || '-', type: 'info' }
    },
    translateReceiptStatus(status) {
      const map = {
        SUBMITTED: { label: '待审核', type: 'warning' },
        APPROVED: { label: '已通过', type: 'success' },
        REJECTED: { label: '已驳回', type: 'danger' }
      }
      return map[status] || { label: status || '-', type: 'info' }
    }
  }
}
</script>

<style scoped>
.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.filter-form {
  margin-bottom: 16px;
}
.drawer-toolbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12px;
}
.drawer-meta span {
  margin-right: 16px;
  color: #909399;
}
.upload-tip {
  margin-left: 10px;
  color: #409eff;
}
</style>
